package core.util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Utilities {
	public static final String COOKIE_NAME = "CS5300SESSIONSESSION";

	private static final Random callIdRand = new Random();

	public static final int RPC_MAX_PACKET_SIZE = 1024;

	public static final int RPC_SOCKET_TIMEOUT = 2000;

	public static final int PING_TIMEOUT = 1000;

	public static final int PUT_SEND = 3;

	public static final int PUT_RECV = 2;

	public static final int MAX_PACKET_SIZE = 1024;
	/**
	 * Create a unique session id based on the following parameters
	 * 
	 * @param req
	 *            http request object
	 * @param servletAddr
	 *            information of the processing servlet
	 * @param serverStartTime
	 *            start time of the servlet
	 * @param uniqueCounter
	 *            this is the nth new session
	 * @return unique session id in String
	 * @throws UnsupportedEncodingException
	 * @throws NoSuchAlgorithmException
	 */
	public static String generateUniqueSessionId(HttpServletRequest req,
			String servletAddr, long serverStartTime,
			AtomicInteger uniqueCounter) throws UnsupportedEncodingException,
			NoSuchAlgorithmException {
		// increment the counter
		uniqueCounter.incrementAndGet();

		// construct the unique session id
		String sessionId = servletAddr + serverStartTime + req.getRemoteAddr()
				+ req.getRemotePort() + uniqueCounter.get();

		return sessionId;
	}

	public static void redirectPage(HttpServletResponse response,
			String pageName) throws IOException {
		response.sendRedirect(response.encodeRedirectURL(pageName));
	}

	public static int generatePutCallId() {
		int callId;
		// arbitrary up to 1000
		do {
			callId = callIdRand.nextInt(1000);
		} while (StoredData.putResponseCounter.containsKey(callId));
		return callId;
	}
	
}
